package uk.co.agileworks.bidpirate.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import uk.co.agileworks.bidpirate.model.Region;

@Component
public final class CookieInterceptor implements HandlerInterceptor {

	private static final int ONE_WEEK = 24 * 7 * 60 * 60;

	@Autowired
	private UserSession userSession;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("region")) {
					Region region = Region.valueOf(cookie.getValue());
					userSession.getUser().setRegion(region);
				} else if (cookie.getName().equals("filter")) {
					String filter = cookie.getValue();
					userSession.currentFilter(filter);
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) {
		
		Cookie region = new Cookie("region", userSession.getUser().getRegion().name());
		region.setMaxAge(ONE_WEEK);
		response.addCookie(region);
		
		Cookie filter = new Cookie("filter", userSession.currentFilter(null).name());
		filter.setMaxAge(ONE_WEEK);
		response.addCookie(filter);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception exception) {
	}

}
